from sqlalchemy import Boolean, Column, Integer, String, Float, Text, ForeignKey, Enum, DateTime
from sqlalchemy.orm import relationship
from datetime import datetime
from app.db.base_class import Base
import enum

class ProductStatus(enum.Enum):
    draft = "draft"          # 草稿
    on_sale = "on_sale"      # 在售
    off_sale = "off_sale"    # 下架
    sold_out = "sold_out"    # 售罄

class Category(Base):
    __tablename__ = "categories"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(100), nullable=False)
    description = Column(Text)
    parent_id = Column(Integer, ForeignKey("categories.id"))
    level = Column(Integer, default=1)  # 分类层级
    is_active = Column(Boolean, default=True)

    # 关联
    products = relationship("Product", back_populates="category")
    children = relationship("Category")

class Product(Base):
    __tablename__ = "products"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(255), nullable=False, index=True)
    description = Column(Text)
    price = Column(Float, nullable=False)
    original_price = Column(Float)  # 原价
    category_id = Column(Integer, ForeignKey("categories.id"))
    stock = Column(Integer, default=0)  # 库存数量
    sales = Column(Integer, default=0)  # 销量
    status = Column(Enum(ProductStatus), default=ProductStatus.draft)
    is_featured = Column(Boolean, default=False)  # 是否推荐
    sku = Column(String(100), unique=True)  # 商品编码

    # 溯源信息
    origin_place = Column(String(255))  # 产地
    producer = Column(String(255))      # 生产商
    production_date = Column(DateTime)   # 生产日期
    shelf_life = Column(Integer)        # 保质期(天)

    # 关联
    category = relationship("Category", back_populates="products")
    images = relationship("ProductImage", back_populates="product")
    inventory_records = relationship("InventoryRecord", back_populates="product")

class ProductImage(Base):
    __tablename__ = "product_images"

    id = Column(Integer, primary_key=True, index=True)
    product_id = Column(Integer, ForeignKey("products.id"))
    image_url = Column(String(255), nullable=False)
    is_primary = Column(Boolean, default=False)  # 是否主图
    display_order = Column(Integer, default=0)   # 显示顺序

    # 关联
    product = relationship("Product", back_populates="images")

class InventoryRecord(Base):
    __tablename__ = "inventory_records"

    id = Column(Integer, primary_key=True, index=True)
    product_id = Column(Integer, ForeignKey("products.id"))
    quantity = Column(Integer, nullable=False)  # 变动数量，正数为入库，负数为出库
    type = Column(String(50))  # 记录类型：入库、出库、盘点等
    remark = Column(String(255))  # 备注
    operator = Column(String(100))  # 操作人

    # 关联
    product = relationship("Product", back_populates="inventory_records")